<template>
  <div class="tcp-server module-container">
    <div class="module-header">
      <h2>{{ $t('tcpServer.title') }}</h2>
      <p class="module-description">{{ $t('tcpServer.description') }}</p>
    </div>

    <div class="module-content">
      <!-- 第一行：服务器控制 + 统计信息 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="server-control-card">
            <div slot="header" class="card-header">
              <span>{{ $t('tcpServer.serverControl') }}</span>
              <ConnectionStatus :connected="listening" />
            </div>

            <el-form label-position="top" size="small">
              <el-form-item :label="$t('tcpServer.port')">
                <el-input-number
                  v-model="config.port"
                  :min="1"
                  :max="65535"
                  :disabled="listening"
                  style="width: 100%"
                />
              </el-form-item>

              <el-form-item :label="$t('tcpServer.encoding')">
                <el-select v-model="config.encoding" :disabled="listening" style="width: 100%">
                  <el-option value="utf8" label="UTF-8" />
                  <el-option value="hex" label="HEX" />
                  <el-option value="base64" label="Base64" />
                  <el-option value="ascii" label="ASCII" />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button
                  v-if="!listening"
                  type="primary"
                  icon="el-icon-video-play"
                  style="width: 100%"
                  @click="startServer"
                >
                  {{ $t('tcpServer.startServer') }}
                </el-button>
                <el-button
                  v-else
                  type="danger"
                  icon="el-icon-video-pause"
                  style="width: 100%"
                  @click="stopServer"
                >
                  {{ $t('tcpServer.stopServer') }}
                </el-button>
              </el-form-item>

              <el-form-item v-if="listening">
                <el-alert
                  :title="`${$t('tcpServer.listeningOn')} ${config.port}`"
                  type="success"
                  :closable="false"
                  show-icon
                />
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card class="statistics-card">
            <div slot="header">
              <span>{{ $t('tcpServer.statistics') }}</span>
            </div>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-value">{{ clients.length }}</div>
                  <div class="stat-label">{{ $t('tcpServer.activeClients') }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-value">{{ statistics.totalConnections }}</div>
                  <div class="stat-label">{{ $t('tcpServer.totalConnections') }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-value">{{ statistics.messagesReceived }}</div>
                  <div class="stat-label">{{ $t('tcpServer.messagesReceived') }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-value">{{ statistics.messagesSent }}</div>
                  <div class="stat-label">{{ $t('tcpServer.messagesSent') }}</div>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第二行：已连接客户端 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card class="clients-card">
            <div slot="header">
              <span>{{ $t('tcpServer.connectedClients') }} ({{ clients.length }})</span>
            </div>

            <div v-if="clients.length === 0" class="no-clients">
              <i class="el-icon-user"></i>
              <p>{{ $t('tcpServer.noClients') }}</p>
            </div>

            <el-table v-else :data="clients" size="small" @row-click="selectClient">
              <el-table-column prop="address" :label="$t('tcpServer.address')" />
              <el-table-column prop="port" :label="$t('tcpServer.port')" width="80" />
              <el-table-column :label="$t('tcpServer.status')" width="100" align="center">
                <template>
                  <el-tag type="success" size="mini" class="status-tag">
                    {{ $t('tcpServer.connected') }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column :label="$t('tcpServer.actions')" width="80">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click.stop="disconnectClient(scope.row)"
                  >
                    {{ $t('tcpServer.kick') }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第三行：发送数据 + 消息记录 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="send-card">
            <div slot="header">
              <span>{{ $t('tcpServer.sendData') }}</span>
            </div>

            <el-form label-position="top" size="small">
              <el-form-item :label="$t('tcpServer.sendTo')">
                <el-select 
                  v-model="selectedClient" 
                  :placeholder="$t('tcpServer.selectClient')"
                  style="width: 100%"
                  :disabled="clients.length === 0"
                >
                  <el-option
                    v-for="client in clients"
                    :key="client.id"
                    :label="`${client.address}:${client.port}`"
                    :value="client"
                  />
                  <el-option
                    :label="$t('tcpServer.broadcast')"
                    :value="'all'"
                  />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-input
                  v-model="messageInput"
                  type="textarea"
                  :rows="6"
                  :placeholder="$t('tcpServer.enterMessage')"
                  :disabled="!listening || clients.length === 0"
                />
              </el-form-item>

              <el-form-item>
                <el-checkbox v-model="hexInput">{{ $t('tcpServer.hexInput') }}</el-checkbox>
              </el-form-item>

              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-s-promotion"
                  :disabled="!canSend"
                  style="width: 100%"
                  @click="sendMessage"
                >
                  {{ $t('tcpServer.send') }}
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <el-col :span="16">
          <el-card class="messages-card">
            <div slot="header" class="messages-header">
              <span>{{ $t('tcpServer.messages') }}</span>
              <div class="messages-toolbar">
                <el-select v-model="messageFilter" size="mini" style="width: 200px">
                  <el-option :label="$t('tcpServer.allClients')" value="all" />
                  <el-option
                    v-for="client in clients"
                    :key="client.id"
                    :label="`${client.address}:${client.port}`"
                    :value="client.id"
                  />
                </el-select>
                <el-checkbox v-model="autoScroll">{{ $t('common.autoScroll') }}</el-checkbox>
                <el-button size="mini" @click="clearMessages">{{ $t('common.clear') }}</el-button>
                <el-button size="mini" @click="exportMessages">{{ $t('common.export') }}</el-button>
              </div>
            </div>

            <div class="messages-container" ref="messagesContainer">
              <div v-if="filteredMessages.length === 0" class="no-messages">
                <i class="el-icon-chat-line-round"></i>
                <p>{{ $t('tcpServer.noMessages') }}</p>
              </div>
              
              <div v-else class="messages-list">
                <div
                  v-for="msg in filteredMessages"
                  :key="msg.id"
                  :class="['message-item', `message-${msg.type}`, `message-${msg.direction}`]"
                >
                  <div class="message-header">
                    <span class="message-time">{{ formatTime(msg.timestamp) }}</span>
                    <el-tag 
                      :type="msg.direction === 'in' ? 'success' : msg.direction === 'out' ? 'primary' : 'info'"
                      size="mini"
                      class="direction-tag"
                    >
                      {{ msg.direction === 'in' ? $t('tcpServer.received') : 
                         msg.direction === 'out' ? $t('tcpServer.sent') : 
                         $t('tcpServer.system') }}
                    </el-tag>
                    <span v-if="msg.source" class="message-source">{{ msg.source }}</span>
                    <span v-if="msg.target" class="message-target">→ {{ msg.target }}</span>
                  </div>
                  <div class="message-content">
                    <pre>{{ msg.content }}</pre>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import ConnectionStatus from '../../components/ConnectionStatus.vue'
import messageMixin from '../../mixins/messageMixin'

export default {
  name: 'TcpServer',
  
  components: {
    ConnectionStatus
  },

  mixins: [messageMixin],

  data() {
    return {
      messageInput: '',
      hexInput: false,
      autoScroll: true,
      selectedClient: null,
      messageFilter: 'all',
      statistics: {
        totalConnections: 0,
        messagesReceived: 0,
        messagesSent: 0
      }
    }
  },

  computed: {
    ...mapState('tcpUdp', ['messages']),
    ...mapGetters('tcpUdp', ['tcpServerConfig', 'tcpListening', 'tcpClients']),
    
    config: {
      get() {
        return this.tcpServerConfig
      },
      set(value) {
        this.$store.commit('tcpUdp/SET_TCP_SERVER_CONFIG', value)
      }
    },
    
    listening() {
      return this.tcpListening
    },
    
    clients() {
      return this.tcpClients
    },
    
    canSend() {
      return this.listening && this.clients.length > 0 && this.selectedClient && this.messageInput
    },
    
    filteredMessages() {
      let msgs = this.messages.filter(msg => msg.protocol === 'tcp' && msg.mode === 'server')
      
      if (this.messageFilter !== 'all') {
        msgs = msgs.filter(msg => {
          return msg.clientId === this.messageFilter || msg.target === this.messageFilter
        })
      }
      
      return msgs
    }
  },

  watch: {
    filteredMessages: {
      handler() {
        this.updateStatistics()
        if (this.autoScroll) {
          this.$nextTick(() => {
            const container = this.$refs.messagesContainer
            if (container) {
              container.scrollTop = container.scrollHeight
            }
          })
        }
      },
      deep: true
    },
    
    clients(newClients) {
      if (this.selectedClient && this.selectedClient !== 'all') {
        const stillConnected = newClients.find(c => c.id === this.selectedClient.id)
        if (!stillConnected) {
          this.selectedClient = null
        }
      }
    }
  },

  mounted() {
    this.initializeListeners()
  },

  // Removed beforeDestroy to keep server running when switching pages
  beforeDestroy() {
    if (this.listening) {
      this.stopServer()
    }
  },

  methods: {
    ...mapActions('tcpUdp', [
      'startTcpServer',
      'stopTcpServer',
      'handleIncomingMessage',
      'handleTcpClientConnect',
      'handleTcpClientDisconnect'
    ]),

    async startServer() {
      try {
        await this.$store.dispatch('tcpUdp/startTcpServer')
        this.showSuccess(this.$t('tcpServer.serverStarted'), 'server-start')
      } catch (error) {
        this.showError(this.$t('tcpServer.serverStartFailed') + ': ' + error.message, 'server-start-fail')
      }
    },

    async stopServer() {
      try {
        await this.$store.dispatch('tcpUdp/stopTcpServer')
        this.selectedClient = null
        this.showInfo(this.$t('tcpServer.serverStopped'), 'server-stop')
      } catch (error) {
        this.showError(error.message, 'server-stop-fail')
      }
    },

    selectClient(client) {
      this.selectedClient = client
    },

    async disconnectClient(client) {
      // This would need backend implementation
      this.showInfo(`Disconnecting client ${client.address}:${client.port}`, 'client-disconnect')
    },

    async sendMessage() {
      if (!this.messageInput || !this.selectedClient) return

      let message = this.messageInput
      if (this.hexInput) {
        message = this.hexToBuffer(message)
      }

      try {
        if (this.selectedClient === 'all') {
          // Broadcast to all clients
          for (const client of this.clients) {
            await this.$store.dispatch('tcpUdp/sendTcpMessage', {
              protocol: 'tcp-server',
              message,
              target: client.id
            })
          }
          this.showSuccess(this.$t('tcpServer.broadcastSent'), 'broadcast')
        } else {
          // Send to specific client
          await this.$store.dispatch('tcpUdp/sendTcpMessage', {
            protocol: 'tcp-server',
            message,
            target: this.selectedClient.id
          })
        }
        this.messageInput = ''
      } catch (error) {
        this.showError(this.$t('tcpServer.sendFailed') + ': ' + error.message, 'send-fail')
      }
    },

    clearMessages() {
      this.$store.commit('tcpUdp/CLEAR_MESSAGES')
      this.resetStatistics()
    },

    exportMessages() {
      const data = JSON.stringify(this.filteredMessages, null, 2)
      const blob = new Blob([data], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `tcp-server-messages-${Date.now()}.json`
      a.click()
      URL.revokeObjectURL(url)
    },

    formatTime(timestamp) {
      const date = new Date(timestamp)
      return date.toLocaleTimeString()
    },

    hexToBuffer(hexString) {
      const hex = hexString.replace(/\s/g, '')
      const bytes = []
      for (let i = 0; i < hex.length; i += 2) {
        bytes.push(parseInt(hex.substr(i, 2), 16))
      }
      return Buffer.from(bytes)
    },

    updateStatistics() {
      const messages = this.messages.filter(msg => msg.protocol === 'tcp' && msg.mode === 'server')
      this.statistics.messagesReceived = messages.filter(m => m.direction === 'in').length
      this.statistics.messagesSent = messages.filter(m => m.direction === 'out').length
      this.statistics.totalConnections = this.clients.length
    },

    resetStatistics() {
      this.statistics = {
        totalConnections: 0,
        messagesReceived: 0,
        messagesSent: 0
      }
    },

    initializeListeners() {
      const { tcpUdp } = require('../../utils/electron')
      
      tcpUdp.onTcpData((data) => {
        this.handleIncomingMessage({
          protocol: 'tcp',
          mode: 'server',
          message: data.message,
          source: data.source,
          clientId: data.clientId
        })
      })

      tcpUdp.onTcpClientConnect((client) => {
        this.handleTcpClientConnect(client)
        this.statistics.totalConnections++
        // Throttle client connection messages
        this.showInfo(`${this.$t('tcpServer.clientConnected')}: ${client.address}:${client.port}`, 'client-connect')
      })

      tcpUdp.onTcpClientDisconnect((clientId) => {
        const client = this.clients.find(c => c.id === clientId)
        if (client) {
          // Throttle client disconnection messages
          this.showInfo(`${this.$t('tcpServer.clientDisconnected')}: ${client.address}:${client.port}`, 'client-disconnect')
        }
        this.handleTcpClientDisconnect(clientId)
      })

      tcpUdp.onTcpError((error) => {
        this.showError('TCP Server Error: ' + error.message, 'tcp-error')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';

.tcp-server {
  .server-control-card {
    margin-bottom: $spacing-medium;
    min-height: 320px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .statistics-card {
    margin-bottom: $spacing-medium;
    min-height: 320px;
    
    .stat-item {
      text-align: center;
      padding: $spacing-medium 0;

      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: $primary-color;
        margin-bottom: $spacing-small;
      }

      .stat-label {
        font-size: 12px;
        color: $text-secondary;
      }
    }
  }

  .clients-card {
    margin-bottom: $spacing-medium;
    
    .no-clients {
      text-align: center;
      padding: $spacing-large;
      color: $text-secondary;
      
      i {
        font-size: 32px;
        color: $text-placeholder;
        margin-bottom: $spacing-small;
      }
    }
  }

  .send-card {
    height: 500px;
    margin-bottom: $spacing-medium;
    
    ::v-deep .el-card__body {
      height: calc(100% - 60px); // Account for header height
      overflow-y: auto;
    }
  }

  .messages-card {
    height: 500px;
    margin-bottom: $spacing-medium;
    
    .messages-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .messages-toolbar {
        display: flex;
        gap: $spacing-small;
        align-items: center;
      }
    }

    .messages-container {
      height: 400px;
      overflow-y: auto;
      background: $background-color-base;
      border-radius: $border-radius-base;
      padding: $spacing-medium;

      .no-messages {
        text-align: center;
        color: $text-regular;
        padding: $spacing-extra-large;
        
        i {
          font-size: 48px;
          color: $text-placeholder;
          margin-bottom: $spacing-medium;
        }
      }

      .messages-list {
        display: flex;
        flex-direction: column;
      }

      .message-item {
        margin-bottom: $spacing-medium;
        padding: $spacing-small $spacing-medium;
        border-radius: $border-radius-base;
        border-left: 3px solid transparent;
        background: $card-bg;

        &.message-in {
          border-left-color: $success-color;
        }

        &.message-out {
          border-left-color: $primary-color;
        }

        &.message-system {
          border-left-color: $info-color;
          background: $info-light;
        }

        .message-header {
          display: flex;
          gap: $spacing-small;
          align-items: center;
          margin-bottom: $spacing-small;
          font-size: 12px;

          .message-time {
            color: $text-secondary;
          }

          .message-source,
          .message-target {
            color: $text-secondary;
            margin-left: auto;
          }
        }

        .message-content {
          pre {
            margin: 0;
            font-family: 'Monaco', 'Menlo', monospace;
            font-size: 13px;
            line-height: 1.5;
            white-space: pre-wrap;
            word-break: break-all;
            color: $text-primary;
          }
        }
      }
    }
  }

  // 标签文字居中样式
  .status-tag {
    display: inline-block;
    text-align: center;
    width: 100%;
  }

  .direction-tag {
    display: inline-block;
    text-align: center;
  }
}
</style>